package com.iot.mqtt;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.iot.constants.EventEnum;
import com.iot.entity.DeviceProperty;
import com.iot.repository.DevicePropertyMapper;
import com.iot.ruler.core.Ruler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 设备历史数据处理
 *
 * @author lzb22
 */
@Component
@Slf4j
public class DataMessageReceiveRules extends Ruler<DataMessageReceiveSubject, EventEnum, JSONObject> {

    private final DevicePropertyMapper propertyMapper;

    public DataMessageReceiveRules(DevicePropertyMapper propertyMapper) {
        this.propertyMapper = propertyMapper;
    }

    @Override
    public EventEnum getTag() {
        return EventEnum.MQTT_DATA_SAVE_EVENT;
    }

    /**
     * 模拟判定条件，只要数据量超过500条即做一次true判定
     *
     * @param event 接收到的事件
     * @return true/false
     */
    @Override
    public boolean condition(DataMessageReceiveSubject event) {
        return event.getSource().toString().isEmpty();
    }

    @Override
    public void apply(DataMessageReceiveSubject event) {
        JSONObject body = JSON.parseObject(event.getSource().toString());
        Date now = new Date();
        for (String key : body.keySet()) {
            // 跳过 timestamp 字段本身
            if ("timestamp".equalsIgnoreCase(key)) continue;

            Object value = body.get(key);
            if (value == null) continue;

            DeviceProperty prop = new DeviceProperty();
            prop.setDeviceId(body.getString("deviceId"));
            prop.setPropertyKey(key);
            prop.setPropertyValue(value.toString());
            prop.setTimestamp(now);
            propertyMapper.insert(prop);
        }
    }

    @Override
    public void publish(JSONObject dataJson) {
    }
}
